package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.model.NFCResult;
import com.adtech.farmProducts.model.SourceInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.hachi.publishplugin.activity.CertPlugin;
import com.hachi.publishplugin.bean.Result;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2020/6/20
 * Created by xiaocz
 * Describe 消费者-查询端
 */
public class CSearchActivity extends BaseNfcActivity {

    @BindView(R.id.edit_search)
    EditText edit_search;
    private int position;

    public static void show(Context context,int position) {
        Intent intent = new Intent(context, CSearchActivity.class);
        intent.putExtra("position",position);
        context.startActivity(intent);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if(bundle!=null){
            position=bundle.getInt("position");
        }
        return super.initArgs(bundle);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_c_search;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColor(R.color.trans).init();
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    String searchValue = String.valueOf(edit_search.getText()).trim();
                    if (!TextUtils.isEmpty(searchValue)) {
                        searchInfo(searchValue);
                    } else {
                        App.getInstance().showMessage("请输入或扫描获取溯源码！");
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        isNFC();
    }

    @OnClick({R.id.left_back, R.id.btn_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_back:
                if(position==0){
                    LaunchActivity.show(mContext);
                    finish();
                }else {
                    finish();
                }
                break;
            case R.id.btn_search:
                String searchValue = String.valueOf(edit_search.getText()).trim();
                if (!TextUtils.isEmpty(searchValue)) {
                    searchInfo(searchValue);
                } else {
                    App.getInstance().showMessage("请输入或扫描获取溯源码！");
                }
                break;
        }
    }

    private void searchInfo(String searchValue) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        HashMap<String, String> data = new HashMap<>();
        data.put("handleType", "");
        data.put("sourceCode", searchValue);
        data.put("userId", "");
        asyncHttpPostFormData.addFormData("data", data);
        asyncHttpPostFormData.addFormData("pageIndex", 1);
        asyncHttpPostFormData.addFormData("PageSize", Common.Constant.pageSize);
        okHttpClient.posts(Common.Constant.API_IP + "handle/queryHistory", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<List<SourceInfo>>>() {
                }.getType();
                RspModel<ArrayList<SourceInfo>> rspModel = getAnalysis(response, type, "溯源详情");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            CSourceInfoActivity.show(mContext, rspModel.getData());
                        } else {
                            App.getInstance().showMessage("系统中暂无该溯源码！");
                        }
                        break;
                    default:
                        App.getInstance().showMessage("查询失败！");
                        break;
                }
            }
        });
    }


    @Override
    protected void onNewIntent(Intent intent) {
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        NFCResult result = resolveVerifyIntent(detectedTag);
        if (result != null) {
            if(result.isState()){
                edit_search.setText(result.getResult().getUid());
                searchInfo(result.getResult().getUid());
            }else {
                App.getInstance().showMessage(result.getMessage());
            }
        }
    }
}
